import jwt
from datetime import datetime
from .conf import jwt_settings


class JwtToken:
    @classmethod
    def get_token(cls, user):
        # payload的数据包含用户名和用户id
        payload = {
            'username': user.username,
            'id': user.id,
            # 公共声明
            'exp': datetime.utcnow() + jwt_settings.ACCESS_TOKEN_LIFETIME,  # (Expiration Time) token的过期时间的时间戳
            'iat': datetime.utcnow(),  # (Issued At) 创建时间的时间戳
        }
        jwt_encode = jwt.encode(payload, jwt_settings.SIGNING_KEY, algorithm=jwt_settings.ALGORITHM)
        return jwt_encode

    @classmethod
    def get_payload(cls, token):
        # 解析token成payload
        options = {'verify_exp': True}  # options中verify_exp为Ture，jwt.decode会取出payload中的exp校验时间是否过期
        payload = jwt.decode(token, jwt_settings.SIGNING_KEY, algorithms=[jwt_settings.ALGORITHM], options=options)
        return payload


